<?php
/**
 * Created by 784855684@qq.com.
 * Link: https://github.com/lichtung/wshore
 * User: linzh
 * Date: 6/25/17
 * Time: 6:11 PM
 */
declare(strict_types=1);


namespace wshore\library;


class TreeSort
{

    protected $list = null;

    protected $nested = [];
    protected $leveld = [];

    public function __construct(array $list)
    {
        $this->list = $list;
        $list = [];
        foreach ($this->list as $key => $item) {
            if ($item['pid'] == 0) {
                $item['children'] = [];
                $id = $item['id'];
                $list[$id] = $item;
                unset($this->list[$key]);
                $this->_build($list[$id]);
            }
        }
        $this->nested = $list;
    }

    private function _build(array &$item)
    {
        $id = $item['id'];
        foreach ($this->list as $k => $v) {
            if ($v['pid'] == $id) {
                $vid = $v['id'];
                $item['children'][$vid] = $v;
                unset($this->list[$k]);
                $this->_build($item['children'][$vid]);
            }
        }
    }

    private function _debuild(&$list, $level = 0)
    {
        foreach ($list as $item) {
            $item['level'] = $level;
            $this->leveld[] = $item;
            if (!empty($item['children'])) {
                $this->_debuild($item['children'], $level + 1);
            }
        }
        foreach ($this->leveld as &$item) {
            unset($item['children']);
        }
    }

    /**
     * @param bool $nested 是否转为嵌套的列表
     * @return array
     */
    public function tolist($nested = true): array
    {
        if ($nested) {
            return $this->nested;
        } else {
            $this->_debuild($this->nested, 0);
            return $this->leveld;
        }
    }

}